package com.ruoyi.iot.exchange.network.tcp.handler.impl;

import com.ruoyi.iot.domain.IotDevice;
import com.ruoyi.iot.domain.IotFrame;
import com.ruoyi.iot.domain.dto.ExchangeDTO;
import com.ruoyi.iot.exchange.network.tcp.cache.TcpChannelCache;
import com.ruoyi.iot.exchange.network.tcp.handler.dispatch.TCPDispatchHandler;
import com.ruoyi.iot.rabbitmq.ExchangeRabbitHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.util.HexBin;


@Slf4j
public class HexHeadTailDispatchHandler extends TCPDispatchHandler  {

    public HexHeadTailDispatchHandler(IotFrame iotFrame) {
        super(iotFrame);
    }





    /**
     * 解析当前帧
     * @return
     */
    @Override
    public void decodeFrame(){
       String tailHex =  iotFrame.getLenIndexList();
       byte[] tailMark = HexBin.stringToBytes(tailHex);
       byte[] temp = new byte[tailMark.length];
       byte[] frame = null;
       do {
           in.readBytes(temp);
           String tempHex = HexBin.bytesToString(temp);
           //log.info("ht_trim: tailMark" + tailHex + " tempHex:" + tempHex);
           if(tempHex.equals(tailHex)) {
             int len =   in.writerIndex() - in.readerIndex() + temp.length ;
             byte[] total = new byte[len];
             in.resetReaderIndex();
             in.readBytes(total);
             log.info("ht total:" + HexBin.bytesToString(total));
             frame = total;
             in.markReaderIndex();
             break;
           }
       }while (in.writerIndex() - in.readerIndex()  >= temp.length);
        String devCode = TcpChannelCache.getDevId(channel);
        IotDevice iotDeviceDTO = findDevice(devCode);
        // log.info("devCode:" + devCode);
        if(iotDeviceDTO == null) {
            log.info(String.format("devCode:%s loss!",devCode));
            return;
        }
        ExchangeDTO exchangeDTO = new ExchangeDTO();
        byte[] hexFrame = patternHex(frame);
        exchangeDTO.setData(hexFrame);
        exchangeDTO.setDevId(devCode);

        exchangeDTO.setProductId(iotDeviceDTO.getProductId());
        ExchangeRabbitHelper.getInstance().devPublishToMQ(exchangeDTO);
        log.info("exchangeDTO:" + exchangeDTO.toString());
    }


    @Override
    protected byte[] patternHex(byte[] frame) {
        Long residueLen = frame.length - (iotFrame.getDataLeftVector() + iotFrame.getDataRightVector());
        byte[] dstBuff = new byte[residueLen.intValue()];
        System.arraycopy(frame,iotFrame.getDataLeftVector().intValue(),dstBuff,0,residueLen.intValue());

        log.info("dst total:" + HexBin.bytesToString(dstBuff));

        return dstBuff;
    }

    @Override
    protected String takeDevId(byte[] frame) {
        return null;
    }

    @Override
    protected Integer getDataLen(byte[] dataLenBuff) {
        return null;
    }

}
